#!coding=utf-8
#!/usr/bin/python
import socket
import select
import datetime
import time
import threading
"""
py代理穿透客户端

"""

socket.setdefaulttimeout(3)

def auth_token(conn):
    conn.send(token)
    data = conn.recv(1)
    if data == "1":
        return True
    else:
        print "shibai ",data
        return False

def py_cliet():
    #pyserver服务端连接
    socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket_server.connect(pyserver)
    if auth_token(socket_server):
        print "py_client 注册成功"
    else:
        print "py_client 注册失败"
        socket_server.close()
        return False
    #被控制机连接
    local_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    local_socket.connect(remote_address)
    inputs=[socket_server,local_socket]
    outputs=[]
    excepts=[]
    bind_users={}
    #绑定
    bind_users[local_socket] = socket_server
    bind_users[socket_server] = local_socket

    while True:
        readable, writable, exceptional = select.select(inputs, outputs, excepts)
        for i in readable:
            try:
                data = i.recv(1024)
            except Exception, e:
                print "数据接收失败", e
                data = ""
            # 处理数据
            if not len(data) == 0:
                # 转发数据
                try:
                    bind_users[i].send(data)
                except Exception, e:
                    pass
                    # print e,"数据发送异常了"

            else:
                # 客户端异常断开了
                print "异常断开了，删除用户", repr(data)
                try:
                    c1 = bind_users.get(i, None)
                    c2 = bind_users.get(c1, None)

                    for i2 in [c1, c2]:
                        if i2:
                            i2.close()
                            del bind_users[i2]
                        i.shutdown(2)
                        i.close()
                        inputs.remove(i)
                except Exception, e:
                    i.shutdown(2)
                    i.close()
                    inputs.remove(i)
                    print e, "客户端异常"
                print bind_users
                print inputs

def try_py_clinet():
    try:
        py_cliet()
    except Exception,e:
        print "新连接建立失败",e

def run():
    while True:
        if threading.activeCount() <=10:
            print threading.activeCount()
            t = threading.Thread(target=try_py_clinet)
            t.setDaemon(True)
            t.start()
        time.sleep(1)

if __name__ == '__main__':
    #认证token需和PyServer里的token一致
    token = "XhYno123456789"
    #配置远程代理服务器地址
    pyserver = ("x.x.x.x",9999)
    #配置被控制win主机地址
    remote_address = ("127.0.0.1", 3389)
    run()

